<?php

namespace App\Console\Commands;

use App\Jobs\ProcessDispatch;
use App\Tools\FindTasks;
use App\Tools\Logs;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;

class RunDispatch extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dispatch:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '执行派单程序';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $findTasks = new FindTasks();
        // 获取需要执行的派单任务
        $allTasks = $findTasks->getList();

        Log::info("本次队列执行的派单数量: ".count($allTasks));
        if (empty($allTasks)) {
            return;
        }

        // 进入派单队列
        $dispatch_task_code = [];
        foreach ($allTasks as $value) {
            if (Redis::exists("dispatch_task_code")) {
                $dispatch_task_code = json_decode(Redis::get("dispatch_task_code"), true);
                if (in_array($value['id'], $dispatch_task_code)) {
                    Log::info("{$value['id']} 有任务跳过");
                    continue;
                }
            }
            $dispatch_task_code[] = $value['id'];
            Redis::set("dispatch_task_code", json_encode($dispatch_task_code));
            ProcessDispatch::dispatch($value);
        }
    }
}
